package cn.dida.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.exception.BizzException;
import cn.dida.model.Branch;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.UserSession;
import cn.dida.service.BranchService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;

/**
 * 网点管理
 * @author weiwei
 */
@Controller
public class BranchController extends BaseController {
    @Autowired
    private BranchService branchService;

    /**
     * 网点列表
	 * @param keyword 查询条件
	 * @param state 网点状态,1正常，2停用
	 * @param page 分页游标
	 * @return ModelAndView
     * */
    @GetMapping("/branch")
    public ModelAndView branch(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);

        Pageable<Branch> branchList = branchService.queryBranch(userSession.getCompanyId(), keyword, state, page);
        model.put("branchList", branchList);
        model.put("keyword", keyword);
        model.put("state", state);
        return new ModelAndView("branch_list").addAllObjects(model);
    }

    /**
     * 网点数据导出
     * @param keyword   查询条件
     * @param state     网点状态：1正常，2停用
     * @return ModelAndView
     */
    @GetMapping("/branch/export")
    public ModelAndView branch_export(HttpServletRequest request, HttpServletResponse response, String keyword, Integer state) throws Exception {
        UserSession userSession = getUserSession(request);
        Map<String, Object> paramMap = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(keyword)) {//网点名称
            paramMap.put("keyword", keyword);
        }
        if (state != null) {
            paramMap.put("state", state);
        }

        List<Branch> exportList = branchService.queryBranchForExport(userSession.getCompanyId(), keyword, state);

        String fileName = "网点管理数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (Branch obj : exportList) {
            fmap = new HashMap<String, Object>();
            Long tid = NumberUtils.toLong(obj.getId().toString(), 0L);
            fmap.put("id", tid);
            fmap.put("name", obj.getName());
            fmap.put("linkMan", obj.getLinkMan());
            fmap.put("linkPhone", obj.getLinkPhone());
            fmap.put("address", obj.getAddress());
            if (obj.getState() == 1) {
                fmap.put("state", "正常");
            } else if (obj.getState() == 2) {
                fmap.put("state", "停用");
            }
            fmap.put("remark", obj.getRemark());

            list.add(fmap);
        }

        String columnNames[] = {"ID", "兑奖网点", "联系人", "联系电话", "详细地址", "状态", "备注"};//列名
        String keys[] = {"id", "name", "linkMan", "linkPhone", "address", "state", "remark"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

    /**
     * 获取网点列表
     * @param state 网点状态：1正常，2停用
     * @return HttpResponseBodyWrapper 封装网点列表数据
     * */
    @ResponseBody
    @GetMapping(value = "/branch", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpResponseBodyWrapper getBranch(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        List<Branch> branchList = branchService.queryBranch(userSession.getCompanyId(), state);
        model.put("branchList", branchList);
        return new HttpResponseBodyWrapper(branchList);
    }

    /**
     * 新增网点
     * @param branch 网点实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
     * */
    @ResponseBody
    @PostMapping("/branch")
    public HttpResponseBodyWrapper postBranch(HttpServletRequest request, @RequestBody Branch branch) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        branch.setName(StringUtils.trimToNull(branch.getName()));
        branch.setLinkMan(StringUtils.trimToNull(branch.getLinkMan()));
        branch.setLinkPhone(StringUtils.trimToNull(branch.getLinkPhone()));
        branch.setAddress(StringUtils.trimToNull(branch.getAddress()));
        branch.setCompanyId(userSession.getCompanyId());
        branch.setCreateStaffId(userSession.getId());

        if (branch.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入网点名称");
        }
        if (branch.getLinkMan() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入联系人");
        }
        if (branch.getLinkPhone() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入网点手机号");
        }
        if (branch.getAddress() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入详细地址");
        }
        if (branch.getDepartmentId() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请选择部门");
        }
        if (!Pattern.matches("\\d{11}", branch.getLinkPhone())) {
            throw new BizzException(BizzException.error_code_invalid_params, "手机号输入有误");
        }
        if (branchService.getByLinkPhone(userSession.getCompanyId(), branch.getLinkPhone()) != null) {
            throw new BizzException(BizzException.error_code_invalid_params, "已存在手机号为【" + branch.getLinkPhone() + "】的网点");
        }

        Boolean result = branchService.insertBranch(branch);
        return new HttpResponseBodyWrapper(result);
    }
    /**
     * 根据公司id和网点id获取网点
     * @param id 网点id
     * @return HttpResponseBodyWrapper 封装单个网点实体数据
     * */
    @ResponseBody
    @GetMapping("/branch/{id}")
    public HttpResponseBodyWrapper getBranch(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        Branch result = branchService.getBranch(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 更新网点
     * @param branch 网点实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
     * */
    @ResponseBody
    @PutMapping("/branch/{id}")
    public HttpResponseBodyWrapper putBranch(HttpServletRequest request, @RequestBody Branch branch) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        branch.setName(StringUtils.trimToNull(branch.getName()));
        branch.setLinkMan(StringUtils.trimToNull(branch.getLinkMan()));
        branch.setLinkPhone(StringUtils.trimToNull(branch.getLinkPhone()));
        branch.setAddress(StringUtils.trimToNull(branch.getAddress()));
        branch.setCompanyId(userSession.getCompanyId());
        branch.setCreateStaffId(userSession.getId());

        if (branch.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入网点名称");
        }
        if (branch.getLinkMan() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入联系人");
        }
        if (branch.getLinkPhone() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入网点手机号");
        }
        if (branch.getAddress() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入详细地址");
        }
        if (branch.getDepartmentId() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请选择部门");
        }
        if (!Pattern.matches("\\d{11}", branch.getLinkPhone())) {
            throw new BizzException(BizzException.error_code_invalid_params, "手机号输入有误");
        }
        Branch tmp = branchService.getByLinkPhone(userSession.getCompanyId(), branch.getLinkPhone());
        if (tmp != null && tmp.getId().intValue() != branch.getId().intValue()) {
            throw new BizzException(BizzException.error_code_invalid_params, "已存在手机号为【" + branch.getLinkPhone() + "】的网点");
        }

        Boolean result = branchService.updateBranch(branch);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 删除网点
     * @param id 网点id
     * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
     * */
    @ResponseBody
    @DeleteMapping("/branch/{id}")
    public HttpResponseBodyWrapper deleteBranch(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        Boolean result = branchService.deleteBranch(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 删除奖品与网点关联
     * @param branchId 网点id
     * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
     */
    @ResponseBody
    @DeleteMapping("/branch/delete/{branchId}")
    public HttpResponseBodyWrapper deletePB(HttpServletRequest request, @PathVariable int branchId) throws Exception {
        Boolean result = branchService.delPBByBranchId(String.valueOf(branchId));
        return new HttpResponseBodyWrapper(result);
    }
}
